<script setup lang="ts">
import { io, Socket } from "socket.io-client";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getMessageListApi, collectApi } from "../api/message";
import { useUser } from "../hooks/useUser";
import { getChatsRoomGroupUserApi } from "../api/chatsRoom";
import { useGroupUserStore } from "../store/groupUser";
import EmojiPicker, { EmojiExt } from "vue3-emoji-picker";
import { uploadsImg, uploadFile } from "../api/comment";
import "vue3-emoji-picker/css";
import { UploaderFileListItem } from "vant";
import { Numeric } from "vant/lib/utils";

const groupUserStore = useGroupUserStore();

const router = useRouter();

const roomName = computed(
  () => router.currentRoute.value.params.roomName
) as any;

const roomId = computed(() => router.currentRoute.value.params.roomId);

const type = computed(() => router.currentRoute.value.params.type);

const { userInfo } = useUser();

const msgList = ref<any[]>([]);
const msg = ref("");

const show = ref(false);

const actions = ref([
  {
    text: "收藏",
    type: 0,
  },
  {
    text: "删除",
    type: 1,
  },
]);

const onSelect = async (action: { text: string; type: number }) => {
  if (action.type == 0) {
    await collectApi({
      messageId: currentMsg.value!.id,
      type: currentMsg.value!.type,
    });
  }
};

const currentMsg = ref<IMessage>();
const handleShowPopover = (item: IMessage) => {
  currentMsg.value = item;
};

const socket: Socket = io("http://localhost:3000");
socket.on("connect", () => {
  socket.emit("joinRoom", { roomId: 1, userId: 1 });

  socket.on("message", (data) => {
    if (data.type == "joinRoom") {
      msgList.value = [
        ...msgList.value,
        { type: "text", content: `${data.userId} 加入了房间` },
      ];
    } else {
      msgList.value = [...msgList.value, data.message];
    }
  });
});

const sendMsg = async (type: number) => {
  socket.emit("sendMessage", {
    roomId: roomId.value,
    userId: userInfo.value!.id,
    message: { type, content: msg.value },
  });

  await getMessageList();

  msg.value = "";
};

const messageList = ref<IMessage[]>([]);
const getMessageList = async () => {
  const res = await getMessageListApi(+roomId.value);
  messageList.value = res.data;
};

const userList = ref<IGroupUser[]>([]);
const getUserList = async () => {
  const res = await getChatsRoomGroupUserApi(+roomId.value);
  userList.value = res.data;
  groupUserStore.groupUserlist = res.data;
};

const onSelectEmoji = (emoji: EmojiExt) => {
  console.log(emoji.i);
  msg.value += emoji.i;
};

const onRead = (
  items: UploaderFileListItem | UploaderFileListItem[],
  detail: {
    name: Numeric;
    index: number;
  }
) => {
  console.log(items, detail);
  const formData = new FormData();
  formData.append("file", (items as UploaderFileListItem).file as File);

  if (
    (items as UploaderFileListItem).file!.type == "image/png" ||
    (items as UploaderFileListItem).file!.type == "image/jpeg"
  ) {
    uploadsImg(formData).then(async (res) => {
      msg.value = "http://localhost:3000/" + res.data.path;
      await sendMsg(1);
    });
  } else {
    uploadFile(formData).then(async (res) => {
      msg.value = "http://localhost:3000/" + res.data.path;
      await sendMsg(2);
    });
  }
};

onMounted(() => {
  getMessageList();
  if (type.value == 1 + "") {
    getUserList();
  }
});
</script>

<template>
  <div class="chatsDetail">
    <VanNavBar
      :title="roomName + (type == '1' ? `（${userList.length}）` : '')"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    >
      <template #right>
        <van-icon
          @click="
            $router.push({
              name: 'groupDetail',
              query: { roomId: roomId, roomName: roomName },
            })
          "
          size="20"
          name="ellipsis"
        />
      </template>
    </VanNavBar>
    <div class="chatsDetail__msgList">
      <div
        :class="
          item.userId == userInfo!.id
            ? 'chatsDetail__msgList-item--for-me'
            : 'chatsDetail__msgList-item'
        "
        v-for="item in messageList"
      >
        <div class="chatsDetail__msgList-item-sender">
          <img src="../assets/vue.svg" alt="" />
          <span class="chatsDetail__msgList-item-sender-name">{{
            item.user.username
          }}</span>
        </div>

        <van-popover
          :actions="actions"
          v-show="item.id == currentMsg?.id"
          placement="left-end"
          @select="onSelect"
        >
          <template #reference>
            <div
              @click="handleShowPopover(item)"
              :class="
            item.userId == userInfo!.id
              ? 'chatsDetail__msgList-item-content--for-me'
              : 'chatsDetail__msgList-item-content'
          "
            >
              <span
                v-if="item.type == 0"
                class="chatsDetail__msgList-item-content-text"
              >
                {{ item.content }}
              </span>

              <span
                v-if="item.type == 1"
                class="chatsDetail__msgList-item-content-text"
              >
                <img
                  :src="item.content"
                  alt=""
                  accept="image"
                  class="chatsDetail__msgList-item-content-img"
                />
              </span>

              <span
                v-if="item.type == 2"
                class="chatsDetail__msgList-item-content-text"
              >
                <!-- 文件下载 -->
                <a :href="item.content" download>下载文件</a>
              </span>
            </div>
          </template>
        </van-popover>
      </div>
    </div>

    <div class="chatsDetail__bottom">
      <div class="chatsDetail__bottom-msgType">
        <div>
          <van-icon size="25" name="smile-o" @click="show = !show" />
        </div>

        <div>
          <van-uploader :after-read="onRead" :max-count="1">
            <van-icon size="25" name="photo-o" />
          </van-uploader>
        </div>

        <div>
          <van-uploader
            :after-read="onRead"
            :max-count="1"
            accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          >
            <van-icon size="25" name="description-o" />
          </van-uploader>
        </div>
      </div>
      <van-field v-model="msg" center clearable placeholder="请输入聊天内筒">
        <template #button>
          <van-button size="small" type="primary" @click="sendMsg(0)"
            >发送</van-button
          >
        </template>
      </van-field>
    </div>

    <van-popup v-model:show="show" :style="{ padding: '64px' }">
      <emoji-picker @select="onSelectEmoji" />
    </van-popup>
  </div>
</template>
